<script setup lang="ts">
import xtxSwiper from '@/components/xtxSwiper.vue'
import CutsomNavBar from './components/CustomNavbar.vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotBannerAPI } from '@/services/home'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import Category from './components/Category.vue'
import HotBanner from './components/HotBanner.vue'
import xtxGuess from '@/components/XtxGuess.vue'
import type { XtxGuessInstance } from '@/types/component'
import pageScelecton from './components/pageScelecton.vue'

// 轮播图数据
const bannerList = ref<BannerItem[]>([])

//获取轮播图数据
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  // console.log(res.result)
  bannerList.value = res.result
}

// 首页分类数据
const categoryList = ref<CategoryItem[]>([])
// 获取分类
const getCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  console.log(res)
  categoryList.value = res.result
  // console.log(categoryList.value);
}

// 首页热门推荐数据
const hotList = ref<HotItem[]>([])
// 获取热门数据
const getHotBanner = async () => {
  const res = await getHomeHotBannerAPI()
  console.log(res)
  hotList.value = res.result
}

// 页面骨架变量
const isLoading = ref(false)

// 调用
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getCategoryData(), getHotBanner()])
  isLoading.value = false
})

// 滚动触底操作
const onscrolltolower = () => {
  console.log('触底了')
  guessRef.value?.getData()
}
// 获取猜你喜欢组件
const guessRef = ref<XtxGuessInstance>()

const istriggered = ref(false)
// 自定义下拉刷新被触发
const onFresh = async () => {
  // console.log('下拉刷新了')
  istriggered.value = true
  // 同时发送三个异步请求
  guessRef.value?.resetData()
  await Promise.all([
    getHomeBannerData(),
    getCategoryData(),
    getHotBanner(),
    guessRef.value?.getData(),
  ])
  istriggered.value = false
}
</script>

<template>
  <CutsomNavBar />
  <scroll-view
    refresher-enabled
    @refresherrefresh="onFresh"
    :refresher-triggered="istriggered"
    scroll-y
    class="scroll"
    @scrolltolower="onscrolltolower"
  >
    <pageScelecton v-if="isLoading"></pageScelecton>
    <template v-else>
      <xtxSwiper :list="bannerList" />
      <Category :list="categoryList"></Category>
      <HotBanner :list="hotList"></HotBanner>
      <xtxGuess ref="guessRef"></xtxGuess>
    </template>
  </scroll-view>
</template>

<style lang="scss">
//
/* #ifdef APP-ANDROID */
#app,
/* #endif */
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll {
  flex: 1;
}
</style>
